package com.yaodian100.ec.outlet.web;

import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.ec.category.entity.Category;
import com.yaodian100.ec.category.service.CategoryService;
import com.yaodian100.ec.common.EcConstant;
import com.yaodian100.ec.common.web.AbstractAction;
import com.yaodian100.ec.generate.entity.EventImage;
import com.yaodian100.ec.generate.service.GenerateService;
import com.yaodian100.ec.generatepage.web.GenerateHelper;
import com.yaodian100.ec.outlet.entity.Outlet;
import com.yaodian100.ec.outlet.service.OutletService;
import com.yaodian100.ec.product.entity.Brand;
import com.yaodian100.ec.product.service.ProductService;

/**
 * 
 * @author scott.su
 *
 */
public class OutletAction extends AbstractAction {
	
	private static final long serialVersionUID = 5895774185587141070L;

	private final Logger logger = LoggerFactory.getLogger(OutletAction.class);
	
	/* service */
	@Autowired
	private OutletService outletService;
	@Autowired
	private GenerateService generateService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private ProductService productService;
	
	/* 搜寻条件 */
	private String paramName;
	private Date paramStartDate;
	private Date paramEndDate;
	private String[] paramEnable = new String[] { "true", "false" };
	
	private String campaignType = "OUTLET";
	
	/* 表单 */
	private String outletId;
	private Outlet outlet;
	private File mainImg;
	private File insideImg;
	private String startDate;
	private String startTime;
	private String endDate;
	private String endTime;
	
	private String brandId;
	private Brand brand;
	
	/* 类别 */
	private String categoryURL;
	private String categoryStatus;
	
	/* 活动集合 */
	private List<Outlet> campaignList;
	
	private EventImage eventImage;
	
	/* 主页图档限制 */
	private double mainFileSize = 55.0;
	private int mainFileWidth = 600;
	private int mainFileHeight = 180;
	
	/* 内页图档限制 */ // TODO
	private double insideFileSize = 90.0;
	private int insideFileWidth = 950;
	private int insideFileHeight = 285;
	
	public String list() {
		return "list";
	}
	
	public String search() {
		try {
			CommonCriteria cri = new CommonCriteria();
			if (StringUtils.isNotBlank(paramName)) {
				cri.addRlike("campaignName", paramName);
			}
			if (paramStartDate != null) {
				cri.addGe("endDate", DateUtil.getFirstTimestamp(Calendar.DATE, paramStartDate));
			}
			if (paramEndDate != null) {
				cri.addLe("startDate", DateUtil.getLastTimestamp(Calendar.DATE, paramEndDate));
			}
			if (paramEnable != null && paramEnable.length == 1) {
				cri.addEq("enable", Boolean.parseBoolean(paramEnable[0]));
			}
			int entitySize = outletService.getListSize(cri).intValue();
			getPager().setTotalSize(entitySize);
			campaignList = outletService.getList(getPager().getCurrentPage() * getPager().getPageRecord(), getPager().getPageRecord(), cri, new String[]{"startDate", "campaignName asc", "id"});
		} catch (Exception e) {
			addActionError("搜寻失败：" + e.getMessage());
			e.printStackTrace();
		}
		return "list";
	}
	
	public String add() {
		initVariables();
		outletId = "";
		
		Calendar cal = DateUtil.getToday();
		cal.add(Calendar.DATE, 7);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		outlet.setStartDate(cal.getTime());
		
		cal.add(Calendar.MONTH, 1);
		outlet.setEndDate(DateUtil.getLastTimestamp(Calendar.DATE, cal.getTime()));
		
		return "edit";
	}
	
	public String edit() {
		initVariables();
		
		if( StringUtils.isBlank(outletId) ) {
			addActionError("品牌折扣活动不存在, 重新选取");
			return search();
		}
		
		outlet = outletService.get(new Long(outletId));
		
		if( outlet == null ) {
			addActionError("品牌折扣活动不存在, 重新选取");
			return search();
		}
		
		brand = productService.getBrandByBrandId(outlet.getBrandId());
		
		startTime = FastDateFormat.getInstance("HH:mm").format(outlet.getStartDate());
		endTime = FastDateFormat.getInstance("HH:mm").format(outlet.getEndDate());
		try {
			categoryURL = categoryService.makeCategorieURL(outlet.getBrandCategoryId(), false);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "edit";
	}
	
	public String save() {
		int error_flag = 0;
		
		try {
			if( outlet == null ) {
				addActionError("品牌折扣活动不存在, 重新选取");
				return search();
			}
			
			if( !StringUtils.isBlank(outletId) ) {
				Long currentId = new Long(outletId);
				if( outlet.getId().longValue() != currentId.longValue() ) {
					addActionError("资料异动错误, 回覆原始资料, 请勿同时操作两视窗");
					outlet = outletService.get(currentId);
					return "edit";
				}
			}
			
			if( outletValidate() ) {
				if(GenerateHelper.mkDir(campaignType)) {
					String today = FastDateFormat.getInstance(EcConstant.DEFAULT_PATTERN_DATE).format(DateUtil.getToday().getTime());
					if( StringUtils.isBlank(outletId) ) {
						if( validateFile(mainImg, "mainImg", "主页广告图档", mainFileSize, mainFileWidth, mainFileHeight) ) {
							EventImage tmpImage = saveImgFile(mainImg, outlet.getMainImgName(), campaignType);
							if( tmpImage != null ) {
								outlet.setMainImgName(tmpImage.getUuid() + tmpImage.getImgType());
								outlet.setMainImgFolder(today);
							}
						} else {
							error_flag++;
						}
						
						if( validateFile(insideImg, "insideImg", "内页广告图档", insideFileSize, insideFileWidth, insideFileHeight) ) {
							EventImage tmpImage = saveImgFile(insideImg, outlet.getInsideImgName(), campaignType);
							if( tmpImage != null ) {
								outlet.setInsideImgName(tmpImage.getUuid() + tmpImage.getImgType());
								outlet.setInsideImgFolder(today);
							}
						} else {
							error_flag++;
						}
					} else {
						if( mainImg != null ) {
							if( validateFile(mainImg, "mainImg", "主页广告图档", mainFileSize, mainFileWidth, mainFileHeight) ) {
								EventImage tmpImage = saveImgFile(mainImg, outlet.getMainImgName(), campaignType);
								if( tmpImage != null ) {
									outlet.setMainImgName(tmpImage.getUuid() + tmpImage.getImgType());
									outlet.setMainImgFolder(today);
								}
							} else {
								error_flag++;
							}
						}
						
						if( insideImg != null ) {
							if( validateFile(insideImg, "insideImg", "内页广告图档", insideFileSize, insideFileWidth, insideFileHeight) ) {
								EventImage tmpImage = saveImgFile(insideImg, outlet.getInsideImgName(), campaignType);
								if( tmpImage != null ) {
									outlet.setInsideImgName(tmpImage.getUuid() + tmpImage.getImgType());
									outlet.setInsideImgFolder(today);
								}
							} else {
								error_flag++;
							}
						}
					}
				}
				
				outlet.setStartDate(DateUtil.convertStringToDate(EcConstant.PATTERN_TIMESTAMP_HH_MM, startDate + " " + startTime));
				outlet.setEndDate(DateUtil.convertStringToDate(EcConstant.PATTERN_TIMESTAMP_HH_MM, endDate + " " + endTime));
				
				Outlet tmpOutlet = null;
				if (error_flag == 0) {
					if( StringUtils.isBlank(outletId) ) {
						tmpOutlet = outletService.save(outlet);
					} else {
						tmpOutlet = outletService.update(outlet);
					}
				}
				
				// 存檔後執行产档逻辑
				Date date = new Date();
				DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
				outletService.generateOutletList(df.format(date));
				outletService.generateOutletCalendar(df.format(date));
				
				if( tmpOutlet != null && tmpOutlet.getId() != null && error_flag == 0 ) {
					outletId = tmpOutlet.getId().toString();
					addActionMessage("储存成功");
					return edit();
				} else {
					addActionMessage("储存失败");
				}
			}
		} catch (Exception e) {
			addActionError("储存失败：" + e.getMessage());
			e.printStackTrace();
			return "edit";
		}
		return "edit";
	}
	
	public String delete() {
		try {
			if( StringUtils.isBlank(outletId) ) {
				addActionError("品牌折扣活动不存在");
				return search();
			}
			
			outletService.delete( outletService.get(new Long(outletId)) );
		} catch (Exception e) {
			addActionError("删除失败：" + e.getMessage());
			e.printStackTrace();
		}
		return search();
	}
	
	public String createCategoryURL() {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		categoryURL = "";
		categoryStatus = "";
		
		outlet.setStartDate(DateUtil.convertStringToDate(EcConstant.PATTERN_TIMESTAMP_HH_MM, startDate + " " + startTime));
		outlet.setEndDate(DateUtil.convertStringToDate(EcConstant.PATTERN_TIMESTAMP_HH_MM, endDate + " " + endTime));
		
		Category category = categoryService.get( outlet.getBrandCategoryId() );
		try {
			categoryURL = categoryService.makeCategorieURL(outlet.getBrandCategoryId(), false);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(category.getParentId().longValue() != 7447) {
			categoryStatus = "品牌商品分类编号只能填写馆类别下分类1";
		} else if( !outletService.validateCampaignTime(outlet) ) {
			categoryStatus = outlet.getBrandCategoryId() + "于" + df.format(outlet.getStartDate()) + " 至 " + df.format(outlet.getEndDate()) + "已经有活动，请调整活动时间";
		} else if( "".equals(categoryURL) ) {
			categoryStatus = "分类编号"+outlet.getBrandCategoryId()+"不存在";
		}
		return "createCategoryURL";
	}
	
	public String validateBrand() {
		brand = null;
		if( StringUtils.isNotBlank(brandId) ) {
			try {
				brand = productService.getBrandByBrandId(brandId);
			} catch (CoreException e) {
				e.printStackTrace();
			}
		}
		
		return "validateBrand";
	}
	
	private boolean outletValidate() {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		if( StringUtils.isBlank(outlet.getCampaignName()) ) {
			addFieldError("campaignName", "请输入活动名称");
		}
		/*
		if( StringUtils.isBlank(outlet.getMainImgLink()) ) {
			addFieldError("mainImgLink", "请输入主页广告图片点击连结");
		}
		
		if( StringUtils.isBlank(outlet.getInsideImgLink()) ) {
			addFieldError("mainImgLink", "请输入内页广告图片点击连结");
		}
		*/
		if( StringUtils.isBlank(outlet.getBrandId()) ) {
			addFieldError("brandIdParam", "请输入品牌编号ID");
		}
		
		if( outlet.getBrandCategoryId() == null || outlet.getBrandCategoryId().longValue() == 0 ) {
			addFieldError("brandCategoryId", "请输入品牌商品分类编号");
		} else if( !outletService.validateCampaignTime(outlet) ) {
			addFieldError("brandCategoryId", outlet.getBrandCategoryId() + "于" + df.format(outlet.getStartDate()) + " 至 " + df.format(outlet.getEndDate()) + "已经有活动，请调整活动时间");
		}
		
		if (getFieldErrors().isEmpty()) {
			return true;
		} else {
			return false;
		}
	}
	
	private boolean validateFile(File imgFile, String fieldName, String fieldNameMsg, double fileSize,
			int fileWidth, int fileHeight) throws IOException {
		int error_size = 0;
		if (null != imgFile) {
			if ((imgFile.length() / 1024) > fileSize) {
				addFieldError(fieldName, fieldNameMsg + "檔案尺寸不符");
				error_size++;
			}
			
			Image image = ImageIO.read(imgFile);
			if(image != null) {
				if (image.getHeight(null) > fileHeight || image.getWidth(null) > fileWidth) {
					addFieldError(fieldName, fieldNameMsg + "檔案长度/宽度不符");
					error_size++;
				}
			} else 
				error_size++;
			
			if (error_size > 0)
				return false;
			else
				return true;
		} else
			return false;
	}
	
	private EventImage saveImgFile(File imgFile, String fileName, String campaignType) {
		try {
			eventImage = new EventImage();
			eventImage.setImgType(fileName.substring(fileName.lastIndexOf("."), fileName.length()));
			eventImage = generateService.saveEventImage(eventImage);
			boolean result = GenerateHelper.uploadImage(eventImage, imgFile, campaignType);
			if (result) {
				return eventImage;
			}
		} catch (Exception e) {
			logger.info("exception :{}", e.getMessage());
		}
		return null;
	}
	
	private void initVariables() {
		outlet = new Outlet();
		outlet.setCampaignType(campaignType);
		
		mainImg = null;
		insideImg = null;
		
		categoryURL = "";
	}
	
	@Override
	public void prepare() throws Exception {
		super.prepare();
	}

	// Getters & Setters
	public OutletService getOutletService() {
		return outletService;
	}

	public void setOutletService(OutletService outletService) {
		this.outletService = outletService;
	}

	public String getParamName() {
		return paramName;
	}

	public void setParamName(String paramName) {
		this.paramName = paramName;
	}

	public String getParamStartDate() {
		if (paramStartDate != null) {
			return DateUtil.convertDateToString("yyyy-MM-dd", paramStartDate);
		} else {
			return "";
		}
	}

	public void setParamStartDate(String paramStartDate) {
		if (StringUtils.isNotBlank(paramStartDate)) {
			if (paramStartDate.indexOf("/") != -1) {
				this.paramStartDate = DateUtil.convertStringToDate("yyyy/MM/dd", paramStartDate);
			} else if (paramStartDate.indexOf("-") != -1) {
				this.paramStartDate = DateUtil.convertStringToDate("yyyy-MM-dd", paramStartDate);
			} else {
				this.paramStartDate = DateUtil.convertStringToDate(paramStartDate);
			}
		} else {
			this.paramStartDate = null;
		}
	}

	public String getParamEndDate() {
		if (paramEndDate != null) {
			return DateUtil.convertDateToString("yyyy-MM-dd", paramEndDate);
		} else {
			return "";
		}
	}

	public void setParamEndDate(String paramEndDate) {
		if (StringUtils.isNotBlank(paramEndDate)) {
			if (paramEndDate.indexOf("/") != -1) {
				this.paramEndDate = DateUtil.convertStringToDate("yyyy/MM/dd", paramEndDate);
			} else if (paramEndDate.indexOf("-") != -1) {
				this.paramEndDate = DateUtil.convertStringToDate("yyyy-MM-dd", paramEndDate);
			} else {
				this.paramEndDate = DateUtil.convertStringToDate(paramEndDate);
			}
		} else {
			this.paramEndDate = null;
		}
	}

	public String[] getParamEnable() {
		return paramEnable;
	}

	public void setParamEnable(String[] paramEnable) {
		this.paramEnable = paramEnable;
	}

	public List<Outlet> getCampaignList() {
		return campaignList;
	}

	public void setCampaignList(List<Outlet> campaignList) {
		this.campaignList = campaignList;
	}

	public String getOutletId() {
		return outletId;
	}

	public void setOutletId(String outletId) {
		this.outletId = outletId;
	}

	public Outlet getOutlet() {
		return outlet;
	}

	public void setOutlet(Outlet outlet) {
		this.outlet = outlet;
	}

	public File getMainImg() {
		return mainImg;
	}

	public void setMainImg(File mainImg) {
		this.mainImg = mainImg;
	}

	public File getInsideImg() {
		return insideImg;
	}

	public void setInsideImg(File insideImg) {
		this.insideImg = insideImg;
	}

	public String getStartDate() {
		return startDate;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public String getStartTime() {
		return startTime;
	}

	public void setStartTime(String startTime) {
		this.startTime = startTime;
	}

	public String getEndDate() {
		return endDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public String getEndTime() {
		return endTime;
	}

	public void setEndTime(String endTime) {
		this.endTime = endTime;
	}

	public GenerateService getGenerateService() {
		return generateService;
	}

	public void setGenerateService(GenerateService generateService) {
		this.generateService = generateService;
	}

	public CategoryService getCategoryService() {
		return categoryService;
	}

	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}

	public String getCategoryURL() {
		return categoryURL;
	}

	public void setCategoryURL(String categoryURL) {
		this.categoryURL = categoryURL;
	}

	public String getCategoryStatus() {
		return categoryStatus;
	}

	public void setCategoryStatus(String categoryStatus) {
		this.categoryStatus = categoryStatus;
	}

	public ProductService getProductService() {
		return productService;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public String getBrandId() {
		return brandId;
	}

	public void setBrandId(String brandId) {
		this.brandId = brandId;
	}

	public Brand getBrand() {
		return brand;
	}

	public void setBrand(Brand brand) {
		this.brand = brand;
	}
	
}
